<template>
  <view class="container">
    <!-- 顶部搜索区域优化 -->
    <view class="search-box">
      <view class="search-input-wrap">
        <text class="iconfont icon-search"></text>
        <input 
          type="text" 
          v-model="keyword"
          placeholder="搜索药品名称"
          placeholder-class="placeholder"
          @confirm="handleSearch"
          @input="handleInput"
        />
        <text v-if="keyword" class="clear-btn" @tap="clearSearch">×</text>
      </view>
    </view>

    <!-- 分类和药品列表区域 -->
    <view class="main">
      <!-- 左侧分类导航优化 -->
      <scroll-view scroll-y class="category-nav" show-scrollbar="false">
        <view 
          class="nav-item"
          :class="{ active: !currentCategory }"
          @tap="switchCategory('')"
        >
          <text class="iconfont icon-all"></text>
          <text>全部药品</text>
        </view>
        <view 
          v-for="item in categories" 
          :key="item.id"
          class="nav-item"
          :class="{ active: currentCategory === item.id }"
          @tap="switchCategory(item.id)"
        >
          <text class="iconfont" :class="item.icon"></text>
          <text>{{ item.name }}</text>
        </view>
      </scroll-view>

      <!-- 右侧内容区优化 -->
      <view class="content">
        <!-- 筛选栏优化 -->
        <view class="filter-bar">
          <view 
            v-for="(item, index) in filterOptions" 
            :key="index"
            class="filter-item"
            :class="{ active: filter === item.value }"
            @tap="switchFilter(item.value)"
          >
            <text>{{ item.label }}</text>
            <text class="count" v-if="item.count">({{ item.count }})</text>
          </view>
        </view>

        <!-- 药品列表优化 -->
        <scroll-view 
          scroll-y 
          class="medicine-list"
          @scrolltolower="loadMore"
          lower-threshold="100"
          refresher-enabled
          :refresher-triggered="refreshing"
          @refresherrefresh="onRefresh"
          @refresherpulling="onPulling"
          refresher-threshold="45"
          refresher-default-style="black"
          show-scrollbar="false"
          scroll-anchoring
          enhanced
          bounces="false"
        >
          <view class="list-wrap">
            <view 
              v-for="item in medicineList" 
              :key="item.medicineId"
              class="medicine-item"
              hover-class="item-hover"
              @tap="goDetail(item.medicineId)"
            >
              <image 
                :src="getImageUrl(item)"
                mode="aspectFill"
                class="medicine-img"
                @error="handleImageError($event, item)"
              >
                <view class="img-placeholder" v-if="!item.imageUrl">
                  <text class="iconfont icon-medicine"></text>
                </view>
              </image>
              <view class="info">
                <view class="name-wrap">
                  <text class="name">{{ item.medicineName }}</text>
                  <text class="tag rx" v-if="item.prescriptionCategoryId === 'rx'">处方药</text>
                  <text class="tag otc" v-else>OTC</text>
                </view>
                <view class="spec">规格：{{ item.specification }}</view>
                <view class="category-tag">{{ item.commonCategoryName }}</view>
                <view class="desc" v-if="item.indications">{{ item.indications }}</view>
                <view class="bottom">
                  <view class="price-wrap">
                    <text class="symbol">¥</text>
                    <text class="price">{{ item.price }}</text>
                  </view>
                  <text class="manufacturer">{{ item.manufacturer }}</text>
                </view>
              </view>
            </view>
          </view>

          <!-- 空状态优化 -->
          <view v-if="medicineList.length === 0" class="empty-state">
            <image src="/static/images/empty.png" mode="aspectFit"></image>
            <text>暂无相关药品</text>
          </view>

          <!-- 加载状态优化 -->
          <view v-if="loading" class="loading-state">
            <view class="loading-spinner"></view>
            <text>加载中...</text>
          </view>

          <!-- 加载完成状态 -->
          <view v-if="!hasMore && medicineList.length > 0" class="load-all">
            <text>已经到底啦 ~</text>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script>
import { medicineApi } from '@/api/medicine'

export default {
  data() {
    return {
      keyword: '',
      categories: [],
      currentCategory: '',
      filter: 'all',
      pageNum: 1,
      pageSize: 15,
      medicineList: [],
      loading: false,
      hasMore: true,
      searchTimer: null,
      refreshing: false,
      filterOptions: [
        { label: '全部', value: 'all', count: 0 },
        { label: '非处方药', value: 'otc', count: 0 },
        { label: '处方药', value: 'rx', count: 0 }
      ],
      lastRefreshTime: 0
    }
  },

  async created() {
    try {
      uni.showLoading({
        title: '加载中...',
        mask: true
      })
      
      await this.loadCategories()
      await this.loadMedicineList(true)
    } catch (e) {
      console.error('初始化失败:', e)
    } finally {
      uni.hideLoading()
    }
  },

  methods: {
    // 加载分类
    async loadCategories() {
      try {
        const res = await medicineApi.getCategories()
        console.log('分类数据:', res)
        if(res.code === 200 && res.data) {
          // 确保分类数据格式正确
          this.categories = res.data.map(item => ({
            id: item.id,
            name: item.name,
            icon: item.icon
          }))
        }
      } catch(e) {
        console.error('获取分类失败:', e)
        uni.showToast({
          title: '获取分类失败',
          icon: 'none'
        })
      }
    },

    // 加载药品列表
    async loadMedicineList(reset = false) {
      if(this.loading && !reset) return
      this.loading = true

      try {
        if(reset) {
          this.pageNum = 1
          this.medicineList = []
          this.hasMore = true
        }

        const params = {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          categoryId: this.currentCategory,
          keyword: this.keyword,
          prescriptionType: this.filter === 'all' ? '' : this.filter
        }
        
        console.log('请求参数:', JSON.stringify(params))

        const res = await medicineApi.getMedicineList(params)
        console.log('药品列表响应:', JSON.stringify(res))

        if(res.code === 200 && res.data) {
          const { records, total, current, pages } = res.data
          
          if(records && records.length > 0) {
            const formattedRecords = records.map(item => ({
              medicineId: item.medicineId,
              medicineName: item.medicineName,
              specification: item.specification,
              manufacturer: item.manufacturer,
              commonCategoryName: item.commonCategoryName,
              prescriptionCategoryName: item.prescriptionCategoryName,
              prescriptionCategoryId: item.prescriptionCategoryId,
              price: item.price,
              stockQuantity: item.stockQuantity,
              imageUrl: item.imageUrl,
              indications: item.indications
            }))
            
            if(reset) {
              this.medicineList = formattedRecords
            } else {
              this.medicineList = [...this.medicineList, ...formattedRecords]
            }
            
            this.hasMore = this.pageNum < pages
            if (this.hasMore) {
              this.pageNum = current + 1
            }
            
            console.log(`已加载 ${this.medicineList.length}/${total} 条数据，当前页码: ${current}/${pages}`)
          } else {
            if (reset) {
              this.medicineList = []
            }
            this.hasMore = false
            console.log('没有查询到数据或数据已全部加载')
          }

          // 更新筛选项的数量统计
          this.updateFilterCounts({
            total: total || 0,
            otcCount: res.data.otcCount || 0,
            rxCount: res.data.rxCount || 0
          })
        } else {
          throw new Error(res.msg || '获取药品列表失败')
        }
      } catch(e) {
        console.error('获取药品列表失败:', e)
        uni.showToast({
          title: e.message || '获取药品列表失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
        if(reset) {
          this.refreshing = false
          uni.stopPullDownRefresh()
        }
      }
    },

    // 切换分类
    switchCategory(id) {
      console.log('切换到分类:', id)
      this.currentCategory = id
      this.loadMedicineList(true)
    },

    // 切换筛选
    switchFilter(type) {
      if(this.filter === type) return
      this.filter = type
      this.loadMedicineList(true)
    },

    // 加载更多
    loadMore() {
      console.log('触发加载更多', this.hasMore, this.loading)
      if(!this.hasMore || this.loading) return
      
      this.pageNum++
      
      uni.showLoading({
        title: '加载更多...'
      })
      
      this.loadMedicineList().finally(() => {
        uni.hideLoading()
      })
    },

    // 跳转详情
    goDetail(id) {
      uni.navigateTo({
        url: `/pages/pharmacy/detail?id=${id}`
      })
    },

    // 处理图片加载失败
    handleImageError(e, item) {
      console.log('图片加载失败:', item.imageUrl)
      // 更新为默认图片路径
      item.imageUrl = ''
    },

    // 搜索防抖
    handleInput() {
      if(this.searchTimer) {
        clearTimeout(this.searchTimer)
      }
      this.searchTimer = setTimeout(() => {
        this.handleSearch()
      }, 300)
    },

    // 清空搜索
    clearSearch() {
      this.keyword = ''
      this.handleSearch()
    },

    // 下拉刷新
    async onRefresh() {
      // 限制刷新频率，至少间隔1秒
      const now = Date.now()
      if (now - this.lastRefreshTime < 1000) {
        this.refreshing = false
        return
      }
      
      this.refreshing = true
      this.lastRefreshTime = now
      console.log('触发下拉刷新')

      try {
        // 重置页码与列表
        this.pageNum = 1
        this.medicineList = []
        this.hasMore = true
        
        // 重新加载数据
        await this.loadMedicineList(true)
        
        // 显示刷新成功提示
        uni.showToast({
          title: '刷新成功',
          icon: 'success',
          duration: 1000
        })
      } catch (e) {
        console.error('刷新失败:', e)
        uni.showToast({
          title: '刷新失败',
          icon: 'none'
        })
      } finally {
        this.refreshing = false
        uni.stopPullDownRefresh()
      }
    },

    // 下拉过程中的处理
    onPulling(e) {
      // 可以根据下拉距离添加一些动画效果
      console.log('pulling', e)
    },

    // 更新筛选项的数量统计
    updateFilterCounts(data) {
      const { otcCount = 0, rxCount = 0, total = 0 } = data
      this.filterOptions = [
        { label: '全部', value: 'all', count: total },
        { label: '非处方药', value: 'otc', count: otcCount },
        { label: '处方药', value: 'rx', count: rxCount }
      ]
    },

    // 处理搜索
    handleSearch() {
      if(this.searchTimer) {
        clearTimeout(this.searchTimer)
      }
      this.searchTimer = setTimeout(() => {
        this.loadMedicineList(true)
      }, 300)
    },

    // 获取药品图片URL
    getImageUrl(item) {
      const baseUrl = 'http://localhost:8188'  // 与request.js中的BASE_URL保持一致
      if (item.imageUrl && item.imageUrl.trim() !== '') {
        // 检查是否已经是完整URL
        if (item.imageUrl.startsWith('http')) {
          return item.imageUrl
        }
        return `${baseUrl}/api/medicine/image/${item.imageUrl}`
      }
      return '/static/medicine/default.jpg'
    }
  },

  // 添加下拉刷新
  onPullDownRefresh() {
    this.loadMedicineList(true)
  }
}
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f6f7fb;
  overflow: hidden;
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;

  .search-box {
    padding: 24rpx;
    background: #fff;
    position: relative;
    box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
    
    .search-input-wrap {
      position: relative;
      display: flex;
      align-items: center;
      height: 72rpx;
      background: #f5f6fa;
      border-radius: 36rpx;
      padding: 0 30rpx;
      
      .icon-search {
        font-size: 32rpx;
        color: #999;
        margin-right: 16rpx;
      }
      
      input {
        flex: 1;
        height: 100%;
        font-size: 28rpx;
      }
      
      .placeholder {
        color: #999;
      }
      
      .clear-btn {
        padding: 10rpx;
        color: #999;
        font-size: 32rpx;
      }
    }
  }

  .main {
    flex: 1;
    display: flex;
    overflow: hidden;
  }

  .category-nav {
    width: 180rpx;
    background: #fff;
    box-shadow: 2rpx 0 10rpx rgba(0,0,0,0.05);
    
    .nav-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 120rpx;
      position: relative;
      
      .iconfont {
        font-size: 40rpx;
        color: #666;
        margin-bottom: 8rpx;
      }
      
      text {
        font-size: 24rpx;
        color: #666;
      }
      
      &.active {
        background: #f6f7fb;
        
        &::before {
          content: '';
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
          width: 6rpx;
          height: 40rpx;
          background: #1890ff;
          border-radius: 0 3rpx 3rpx 0;
        }
        
        .iconfont, text {
          color: #1890ff;
          font-weight: 500;
        }
      }
    }
  }

  .content {
    flex: 1;
    display: flex;
    flex-direction: column;
    margin-left: 20rpx;
    height: 100%;
    overflow: hidden;
    
    .filter-bar {
      display: flex;
      padding: 20rpx;
      background: #fff;
      border-radius: 16rpx;
      margin: 20rpx 20rpx 0;
      box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
      
      .filter-item {
        display: flex;
        align-items: center;
        margin-right: 40rpx;
        
        text {
          font-size: 28rpx;
          color: #666;
        }
        
        .count {
          font-size: 24rpx;
          color: #999;
          margin-left: 4rpx;
        }
        
        &.active {
          text {
            color: #1890ff;
            font-weight: 500;
          }
        }
      }
    }

    .medicine-list {
      flex: 1;
      padding: 20rpx;
      height: calc(100% - 100rpx);
      
      .list-wrap {
        display: flex;
        flex-direction: column;
        gap: 20rpx;
      }
      
      .medicine-item {
        display: flex;
        padding: 20rpx;
        background: #fff;
        border-radius: 16rpx;
        box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
        transition: all 0.2s;
        animation: fadeIn 0.3s ease-in-out;
        
        &.item-hover {
          transform: scale(0.98);
          background: #f8f9fc;
        }
        
        .medicine-img {
          width: 180rpx;
          height: 180rpx;
          border-radius: 12rpx;
          margin-right: 24rpx;
          background: #f5f6fa;
          position: relative;
          
          .img-placeholder {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            
            .icon-medicine {
              font-size: 60rpx;
              color: #ccc;
            }
          }
        }
        
        .info {
          flex: 1;
          display: flex;
          flex-direction: column;
          
          .name-wrap {
            display: flex;
            align-items: center;
            margin-bottom: 12rpx;
            
            .name {
              flex: 1;
              font-size: 30rpx;
              font-weight: 500;
              color: #333;
            }
            
            .tag {
              padding: 4rpx 12rpx;
              border-radius: 4rpx;
              font-size: 22rpx;
              margin-left: 12rpx;
              
              &.rx {
                color: #ff4d4f;
                background: rgba(255,77,79,0.1);
              }
              
              &.otc {
                color: #52c41a;
                background: rgba(82,196,26,0.1);
              }
            }
          }
          
          .spec {
            font-size: 26rpx;
            color: #666;
            margin-bottom: 12rpx;
          }
          
          .category-tag {
            display: inline-block;
            padding: 4rpx 16rpx;
            background: #f0f5ff;
            border-radius: 4rpx;
            font-size: 24rpx;
            color: #1890ff;
            margin-bottom: 12rpx;
          }
          
          .desc {
            font-size: 24rpx;
            color: #999;
            margin-bottom: 16rpx;
            -webkit-line-clamp: 2;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-box-orient: vertical;
          }
          
          .bottom {
            display: flex;
            justify-content: space-between;
            align-items: flex-end;
            margin-top: auto;
            
            .price-wrap {
              display: flex;
              align-items: baseline;
              
              .symbol {
                font-size: 24rpx;
                color: #ff4d4f;
                margin-right: 2rpx;
              }
              
              .price {
                font-size: 36rpx;
                font-weight: 600;
                color: #ff4d4f;
              }
            }
            
            .manufacturer {
              font-size: 24rpx;
              color: #999;
            }
          }
        }
      }
      
      .empty-state {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 60rpx 0;
        
        image {
          width: 240rpx;
          height: 240rpx;
          margin-bottom: 20rpx;
        }
        
        text {
          font-size: 28rpx;
          color: #999;
        }
      }
      
      .loading-state {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 30rpx;
        
        .loading-spinner {
          width: 40rpx;
          height: 40rpx;
          border: 4rpx solid #f3f3f3;
          border-top: 4rpx solid #1890ff;
          border-radius: 50%;
          animation: spin 1s linear infinite;
          margin-right: 12rpx;
        }
        
        text {
          font-size: 26rpx;
          color: #999;
        }
      }
      
      .load-all {
        text-align: center;
        padding: 30rpx;
        color: #999;
        font-size: 26rpx;
      }
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>